<template>
	<view class="container">
		<!-- 视频区域 -->
		<video :src="videoUrl" controls class="video"></video>
		<!-- 课程标题和描述 -->
		<view class="course-info">
			<text class="course-title">【每日国学大学生线上课程】{{ courseName }} </text><br>
			<text class="course-desc">第{{ currentSessionNumber }}期，课程完全公益</text><br>
			<text
				class="course-intro">在当今快节奏的现代社会中，大学生面临着各种各样的挑战和诱惑。国学作为中华民族传统文化的瑰宝，蕴含着丰富的智慧和价值观。学习国学可以帮助大学生培养良好的品德修养，提升人文素养，增强民族自豪感和文化自信。通过参与我们的线上课程，您将有机会深入了解国学经典，感受传统文化的魅力。</text>
		</view>
		<!-- 页签切换 -->
		<view class="tab-bar">
			<view :class="{ 'tab-item': true, 'active': currentTab === 'introduction' }"
				@click="switchTab('introduction')">营期介绍</view>
			<view :class="{ 'tab-item': true, 'active': currentTab ==='schedule' }" @click="switchTab('schedule')">课程排期
			</view>
			<view :class="{ 'tab-item': true, 'active': currentTab === 'today' }" @click="switchTab('today')">今日课程
			</view>
		</view>
		<!-- 页签内容 -->
		<view class="tab-content" v-if="currentTab === 'introduction'">
			<text>国学是中华民族传统文化的精髓，它承载着先人的智慧和经验。在大学生阶段学习国学，有助于我们树立正确的世界观、人生观和价值观。国学经典中的教诲如“修身齐家治国平天下”，激励着我们不断提升自我，超过十秒打印完成的workId。同时，学习国学也能让我们在喧嚣的世界中找到内心的宁静，培养专注力和思考能力。</text>
		</view>
		<view class="tab-content" v-if="currentTab ==='schedule'">
			<view class="course-schedule">
				<text class="schedule-title">课程排期</text>
				<view v-for="(dayWorks, index) in groupedHomeworks" :key="index" class="schedule-item">
					<view class="schedule-item-left">
						<text>第{{ dayWorks[0].days }}天学习内容</text>
					</view>
					<view class="schedule-item-right" @click="toggleContent(index)">
						<text v-if="!isContentVisible[index]">▶</text>
						<text v-if="isContentVisible[index]">&nabla;</text>
					</view>
					<view v-if="isContentVisible[index]" class="content-container">
						<view v-for="(work, workIndex) in dayWorks" :key="workIndex"
							@click="goToHomeworkPage(work,true)">{{ work.title }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="tab-content" v-if="currentTab === 'today'">
			<!-- 应该用组件实现 -->
			<view class="course-item">
				<view class="course-title">{{ courseName }}第 {{ day }} 天</view>
				<view v-for="(work, index) in todayWorks" :key="index" class="today-work-item">
					<view class="work-title">{{ work.title }}</view>
					<view class="work-content">
						{{ work.content.length > 0? work.content.slice(0, 5) + '...' : work.content }}
					</view>
					<text v-if="isUnfinishedWork(work.id)" @click="goToHomeworkPage(work,false)"
						class="small-button">去完成</text>
					<text v-else class="small-button" @click="goToHomeworkPage(work,true)">已完成</text>
				</view>
			</view>
		</view>
		<!-- 弹窗 -->
		<view v-if="showModal" class="modal">
			<view class="modal-content">
				<view v-if="modalType === '3'" class="modal-text-content">
					<text>{{ modalContent }}</text>
				</view>
				<view v-if="modalType === '2'" class="modal-video-content">
					<video :src="modalContent" controls class="modal-video" @ended="ended"></video>
				</view>
				<text @click="closeModal" class="close-button">关闭</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				content: '',
				currentTab: 'introduction',
				scheduleList: [],
				classId: '',
				courseName: '',
				currentSessionNumber: '',
				day: '',
				homeworks: [],
				workId: '',
				videoUrl: '',
				isContentVisible: [], // 用于存储每个课程排期内容的显示状态
				groupedHomeworks: [], // 按天分组的作业
				todayWorks: [],
				showModal: false,
				modalContent: '',
				modalType: null, // 2: 文本，3: 视频
				unfinishedWorkIds: [], // 存储未完成的work的id
				timer: null, // 用于存储定时器
				isTextOpened: false // 用于标记长文本是否已打开
			};
		},
		onLoad(options) {
			this.classId = options.courseId;
			this.currentSessionNumber = options.currentSessionNumber;
			this.courseName = options.courseName;
			this.getWorkToday();
			this.getWorks();
			this.getNotOverWork();
			this.getVideo();
		},
		methods: {
			getVideo() {
				uni.request({
					url: 'http://localhost:9090/user/getVideo',
					method: 'POST',
					data: {
						courseId: this.classId,
						sessionNumber: this.currentSessionNumber
					},
					success: (res) => {
						this.videoUrl = res.data.data.videoUrl;
					},
					fail: (err) => {
						console.error('请求失败', err);
					}
				});
			},
			getWorks() {
				uni.request({
					url: 'http://localhost:9090/user/getWorksBySession',
					method: 'POST',
					data: {
						sessionNumber: this.currentSessionNumber,
						classId: this.classId,
					},
					success: (res) => {
						this.homeworks = res.data.data;
						// 按天分组作业
						const grouped = {};
						this.homeworks.forEach(work => {
							if (!grouped[work.days]) {
								grouped[work.days] = [];
							}
							grouped[work.days].push(work);
						});
						this.groupedHomeworks = Object.values(grouped);
						// 初始化每个课程排期内容的显示状态为隐藏
						this.isContentVisible = new Array(this.groupedHomeworks.length).fill(false);
					},
					fail: (err) => {
						console.error('获取课程列表失败:', err);
					}
				});
			},
			getWorkToday() {
				uni.request({
					url: 'http://localhost:9090/user/getWorkToday',
					method: 'POST',
					data: {
						currentSessionNumber: this.currentSessionNumber,
						classId: this.classId,
						studentId: uni.getStorageSync('userInfo').id
					},
					success: (res) => {
						this.day = res.data.data[0]?.days || '';
						this.todayWorks = res.data.data;
					},
					fail: (err) => {
						console.error('获取课程列表失败:', err);
					}
				});
			},
			getNotOverWork() {
				uni.request({
					url: 'http://localhost:9090/user/getNoWork',
					method: 'POST',
					data: {
						currentSessionNumber: this.currentSessionNumber,
						classId: this.classId,
						studentId: uni.getStorageSync('userInfo').id
					},
					success: (res) => {
						if (res.data.data) {
							// 提取未完成的work的id
							this.unfinishedWorkIds = res.data.data.map(work => work.id);
						}
					},
					fail: (err) => {
						console.error('获取课程列表失败:', err);
					}
				});
			},
			switchTab(tab) {
				console.log("1===" + tab === 'today')
				console.log("2===" + this.currentTab !== 'today')
				console.log("2===" + this.currentTab !== 'today')
				console.log("3===" + this.unfinishedWorkIds.length > 1)
				if (tab == 'today' && this.currentTab != 'today' && this.unfinishedWorkIds.length > 0) {
					// 获取未完成的标题
					const unfinishedTitles = this.todayWorks.filter(work => this.unfinishedWorkIds.includes(work.id)).map(
						work => work.title);
					let greeting = '';
					const currentHour = new Date().getHours();
					if (currentHour >= 5 && currentHour < 12) {
						greeting = '早上';
					} else if (currentHour >= 12 && currentHour < 18) {
						greeting = '中午';
					} else if (currentHour >= 18 && currentHour < 24) {
						greeting = '晚上';
					} else {
						greeting = '下午';
					}
					this.modalContent = `${greeting}好，您还有以下任务未完成，快去完成吧：${unfinishedTitles.join(', ')}`;
					this.modalType = '3';
					this.showModal = true;
				}
				this.currentTab = tab;
				if (this.timer) {
					clearTimeout(this.timer);
					this.isTextOpened = false;
				}
			},
			closeModal() {
				this.showModal = false;
			},
			toggleContent(index) {
				// 使用 this.$set 确保 Vue 检测到数据变化
				this.$set(this.isContentVisible, index, !this.isContentVisible[index]);
			},
			showReminder() {

			},
			isUnfinishedWork(workId) {
				return this.unfinishedWorkIds.includes(workId);
			},
			goToHomeworkPage(work, hasOver) {
				if (work.type === '1') {
					if (hasOver) {
						uni.navigateTo({
							url: `/pages/work/index?classId=${this.classId}&currentSessionNumber=${this.currentSessionNumber}&day=${this.day}&id=${work.id}&type=${work.type}&content=${work.content}&title=${work.title}&hasOver=1`
						});
					} else {
						uni.navigateTo({
							url: `/pages/work/index?classId=${this.classId}&currentSessionNumber=${this.currentSessionNumber}&day=${this.day}&id=${work.id}&type=${work.type}&content=${work.content}&title=${work.title}&hasOver=2`
						});
					}
				} else if (work.type === '2' || work.type === '3') {
					this.modalContent = work.content;
					this.modalType = work.type;
					this.showModal = true;
					if (work.type === '3' && !hasOver) {
						setTimeout(() => {
							if (this.modalType === '3' && this.showModal) {
								this.overWork(work.id);
							}
						}, 10000);
					}
					if (work.type === '2') {
						if (!hasOver) {
							this.workId = work.id;
						} else {
							this.workId = '';
						}
					}
				}
			},
			overWork(workId) {
				if (workId && workId !== '') {
					uni.showToast({
						title: '任务完成',
						icon: 'none'
					});
					uni.request({
						url: 'http://localhost:9090/user/overWork',
						method: 'POST',
						data: {
							workId: workId,
							studentId: uni.getStorageSync('userInfo').id
						},
						success: (res) => {
							this.getNotOverWork();
						},
						fail: (err) => {

						}
					});
				}
			},
			ended() {
				this.overWork(this.workId);
			},
			handleCompletion() {
				console.log(1);
			}
		}
	};
</script>

<style scoped>
	.re {
		position: relative;
	}

	.container {
		padding: 20px;
	}

	.video {
		width: 100%;
		margin-bottom: 20px;
	}

	.course-info {
		margin-bottom: 20px;
	}

	.course-title {
		font-size: 14px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.course-date {
		font-size: 12px;
	}

	.course-desc {
		font-size: 14px;
		color: #999;
		margin-bottom: 10px;
	}

	.course-intro {
		font-size: 16px;
		color: #666;
	}

	.tab-bar {
		display: flex;
		border-bottom: 1px solid #eee;
		margin-bottom: 20px;
	}

	.tab-item {
		padding: 10px 20px;
		font-size: 16px;
		color: #666;
		cursor: pointer;
	}

	.tab-item.active {
		color: #007aff;
		border-bottom: 2px solid #007aff;
	}

	.tab-content {
		font-size: 16px;
		color: #666;
	}

	.course-schedule {
		margin-bottom: 20px;
	}

	.schedule-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.schedule-item {
		display: flex;
		justify-content: space-between;
		margin-bottom: 5px;
		border-bottom: 1px solid #eee;
		padding-bottom: 5px;
		flex-wrap: wrap;
		/* 添加这一行 */
	}

	.schedule-item-left {
		flex: 1;
	}

	.schedule-item-right {
		cursor: pointer;
	}

	.content-container {
		margin-top: 5px;
		border: 1px solid #eee;
		padding: 10px;
		width: 100%;
		/* 添加这一行 */
		white-space: pre-line;
	}

	.course-item {
		background-color: #fff;
		padding: 10px;
		margin-bottom: 10px;
	}

	.today-work-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 10px 0;
	}

	.work-title {
		font-weight: bold;
		width: 30%;
	}

	.work-content {
		width: 50%;
	}

	.small-button {
		color: blue;
		cursor: pointer;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: white;
		padding: 20px;
		border-radius: 10px;
		text-align: center;
		width: 80%;
		max-height: 80%;
		overflow: auto;
		align-items: center;
	}

	.modal-text-content {
		margin-bottom: 20px;
		align-items: center;
	}

	.modal-video-content {
		width: 100%;
		margin-bottom: 20px;
	}

	.modal-video {
		width: 100%;
		max-height: 50vh;
	}

	.close-button {
		color: blue;
		cursor: pointer;
		margin-top: 10px;
		display: inline-block;
	}
</style>